package com.turing.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

public class FileUtils {

    private static Logger log = LoggerFactory.getLogger(FileUtils.class);

    private static void getLabel() {

        String labelPath = "/Users/luoshiwei/Documents/doc/turing/信息抽取/中保登数据样例_v2/反向标注输出结果/13200_label.txt";

        explainLabelResult(labelPath);

    }

    /*
     * 使用合并结果文件解析抽取要素结果
     * */
    public static JSONObject explainMergedLabelResultLocal(String labelPath,String childTaskSn) {
        String mergedLabelStr = readFile(labelPath);
        JSONObject mergedLabelObj = JSONObject.parseObject(mergedLabelStr);
        return explainMergedLabelResult(mergedLabelObj,childTaskSn);
    }

    /*
     * 使用合并结果文件解析抽取要素结果
     * */
    public static JSONObject explainMergedLabelResultRemote(String url,String childTaskSn) {
        String mergedLabelStr = loadJson(url);
        JSONObject mergedLabelObj = JSONObject.parseObject(mergedLabelStr);
        return explainMergedLabelResult(mergedLabelObj,childTaskSn);
    }

    public static JSONObject explainMergedLabelResult(JSONObject mergedLabelObj,String childTaskSn) {


        JSONObject resultObj = new JSONObject();

        for (String key : mergedLabelObj.keySet()) {

            JSONArray eleArr = mergedLabelObj.getJSONArray(key);

            JSONArray groupedArr = new JSONArray();

            for (int i = 0; i < eleArr.size(); i++) {

                JSONObject eleObj = eleArr.getJSONObject(i);

                log.info(">>>>> " + eleObj.toJSONString());
                JSONArray para_info = eleObj.getJSONArray("para_info");
                String firstLine = para_info.getString(0);
                String lastLine = para_info.getString(para_info.size() - 1);

                JSONArray global_pos = eleObj.getJSONArray("global_pos");

                JSONObject obj = new JSONObject();

                obj.put("context", "");   // 上下文
                obj.put("start", global_pos.getInteger(0));  // 要素起始索引
                obj.put("end", global_pos.getInteger(1));  // 要素结束索引
                //                obj.put( "startLineNo", eleInfo.getLineId().split( "_" )[ 2 ] );  // 要素起始行数
                //                obj.put( "endLineNo", eleInfo.getLineId().split( "_" )[ 2 ] );    // 要素结束行数
                obj.put("startLineNo", firstLine.split("_")[2]);
                obj.put("endLineNo", lastLine.split("_")[2]);
                obj.put("lineNo", 0);   // 段落
                obj.put("page", firstLine.split("_")[1]);   // 页码
                obj.put("text", eleObj.getString("value"));   //  要素值
                obj.put("pos", new JSONArray());    // 要素像素坐标

                // 原样输出
                obj.put("para_info", para_info);
                obj.put("pos_info", eleObj.getJSONArray("pos_info"));
                obj.put("degree", eleObj.getString("degree"));
                obj.put("elem_truth", eleObj.getString("elem_truth"));
                obj.put("category", eleObj.getString("elem_name"));
                obj.put("sample_id", eleObj.getString("sample_id"));
                obj.put("global_pos", eleObj.getJSONArray("global_pos"));

                // 生成每条记录的uuid
                obj.put("cus_sample_id", UUID.randomUUID().toString());

                //处理子任务
                String locatedFile = eleObj.get("located_file").toString();
                if (locatedFile.endsWith("_test.json") || locatedFile.endsWith("_mul.json")) {
                    locatedFile = locatedFile.replaceAll("_test.json", ".json").replaceAll("_mul.json", ".json");
                }
                String fileName = locatedFile.substring(locatedFile.lastIndexOf("/") + 1, locatedFile.lastIndexOf("."));

                // 可能还带有标志 如a_test.json, b_mul.json
                //                int extPos = fileName.lastIndexOf( "_" );
                //                if ( extPos!= -1 && extPos>0 ) {
                //                    fileName = fileName.substring( 0, extPos );
                //                }

                log.info("文件名称：" + fileName);
                log.info("parentTaskSn：" + childTaskSn);
                obj.put("parentTaskSn", childTaskSn);

                groupedArr.add(obj);
            }

            resultObj.put(key, groupedArr);
        }

        return resultObj;
    }

    /*
     * 解析抽取要素结果文件
     * */
    public static JSONArray explainLabelResult(String labelPath) {
        List<String> results = readFileByLines(labelPath);

        List<EleInfo> eleInfos = new LinkedList<>();

        for (String result : results) {

            EleInfo eleInfo = EleInfo.requireElementByJson(JSONObject.parseObject(result));
            eleInfos.add(eleInfo);
        }

        // 按要素类型分组
        Map<String, List<EleInfo>> grouped = eleInfos
                .parallelStream()
                .collect(Collectors.groupingBy(EleInfo::getElementCategory));

        JSONArray resultArr = new JSONArray();

        for (String category : grouped.keySet()) {
            JSONArray groupedEleArr = getGroupedEleArr(grouped.get(category));

            resultArr.add(groupedEleArr);
        }

        return resultArr;
    }

    private static JSONArray getGroupedEleArr(List<EleInfo> eleInfos) {
        JSONArray resultArr = new JSONArray();
        if (eleInfos != null && eleInfos.size() > 0) {
            for (EleInfo eleInfo : eleInfos) {
                JSONObject obj = new JSONObject();
                obj.put("context", "");   // 上下文
                obj.put("start", eleInfo.getAllStart());  // 要素起始索引
                obj.put("end", eleInfo.getAllEnd());  // 要素结束索引
                //                obj.put( "startLineNo", eleInfo.getLineId().split( "_" )[ 2 ] );  // 要素起始行数
                //                obj.put( "endLineNo", eleInfo.getLineId().split( "_" )[ 2 ] );    // 要素结束行数
                obj.put("startLineNo", eleInfo.getLineStart());
                obj.put("endLineNo", eleInfo.getLineEnd());
                obj.put("lineNo", eleInfo.getParaNo());   // 段落
                obj.put("page", eleInfo.getPage());   // 页码
                obj.put("text", eleInfo.getElementValue());   //  要素值
                obj.put("pos", new JSONArray());    // 要素像素坐标

                // 原样输出
                obj.put("para_info", eleInfo.getPara_info());
                obj.put("pos_info", eleInfo.getPos_info());
                obj.put("degree", eleInfo.getDegree());
                obj.put("elem_truth", eleInfo.getElem_truth());
                obj.put("category", eleInfo.getElementCategory());
                obj.put("sample_id", eleInfo.getSample_id());

                resultArr.add(obj);
            }
        }
        return resultArr;
    }

    /**
     * @Author：
     * @Description：获取某个目录下所有直接下级文件，不包括目录下的子目录的下的文件，所以不用递归获取
     * @Date：
     */
    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名，不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }

    public static void StringToFile(String content, String path) {

        try {
            File filename = new File(path);
            filename.createNewFile();
            FileWriter fw = new FileWriter(filename);

            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)));
            out.write(content);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static JSONArray getFilesByJson(String path) {
        // 读取resources下的test.json文件
        JSONArray jsonArray = new JSONArray();
//        String s = readJsonFile(path);
      /*  String s1 = s.replaceAll("\\\\\r", "");
        String substring = s1.substring(1, s1.length()-1);*/
        JSONReader reader = null;
        try {
            reader = new JSONReader(new FileReader(path));
            reader.startArray();
            while (reader.hasNext()) {
                JSONObject obj = reader.readObject(JSONObject.class);
                jsonArray.add(obj);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

//         jsonArray = JSON.parseArray(s);

        return jsonArray;
    }


    @Data
    public static class EleInfo {

        private String taskPath;

        private Integer page;

        private Integer paraNo;

        private String lineId;

        private String elementValue;

        private String elementCategory;

        private Integer allStart;

        private Integer allEnd;

        private String elementMarkValue;

        private Integer lineStart;

        private Integer lineEnd;

        private JSONArray para_info;

        private JSONArray pos_info;

        private String degree;

        private String elem_truth;

        private String sample_id;

        private String global_pos;

        public EleInfo() {
        }

        /*
         * {"para_info": ["line_2_18_N0WYzfS9a693"], "pos_info": [8, 10],
         * "elem_name": "回路(回).1", "elem_value": "30", "global_pos": [2569, 2571],
         * "degree": 0.0, "elem_truth": "30"}
         * 结果文件为json
         * */
        public static EleInfo requireElementByJson(JSONObject resultObj) {
            if (resultObj == null) {
                return null;
            }
            EleInfo eleInfo = new EleInfo();
            eleInfo.setElementValue(resultObj.getString("elem_value"));
            eleInfo.setElementMarkValue(resultObj.getString("elem_truth"));
            eleInfo.setElem_truth(resultObj.getString("elem_truth"));
            eleInfo.setDegree(resultObj.getString("degree"));
            eleInfo.setElementCategory(resultObj.getString("elem_name"));
            eleInfo.setSample_id(resultObj.getString("sample_id"));

            JSONArray pos_info = resultObj.getJSONArray("pos_info");
            eleInfo.setPos_info(pos_info);

            // 文本在全文中的位置
            JSONArray global_pos = resultObj.getJSONArray("global_pos");
            eleInfo.setGlobal_pos(global_pos.toJSONString());
            eleInfo.setAllStart(global_pos.getInteger(0));
            eleInfo.setAllEnd(global_pos.getInteger(1));

            JSONArray para_info = resultObj.getJSONArray("para_info");
            eleInfo.setPara_info(para_info);

            int page = 0;
            for (int i = 0; i < para_info.size(); i++) {
                String line = para_info.getString(i);
                if (i == 0) {
                    page = Integer.parseInt(line.split("_")[1]);
                    eleInfo.setLineStart(Integer.parseInt(line.split("_")[2]));
                    eleInfo.setLineId(line);
                }
                if (i == para_info.size() - 1) {
                    eleInfo.setLineEnd(Integer.parseInt(line.split("_")[2]));
                }
            }
            eleInfo.setPage(page);

            return eleInfo;
        }

        public static EleInfo requireElement(String line) {
            if (StringUtils.isEmpty(line)) {
                return null;
            }
            String[] split = line.split("\t");
            if (split.length != 6) {
                System.out.println("line data error!... content is <" + line + ">");
                return null;
            }

            try {
                EleInfo eleInfo = new EleInfo();

                String posStr = split[0];
                String eleV = split[1];
                String eleCat = split[2];
                String eleVPos = split[3];
                String eleMarkV = split[4];
                String eleParaPos = split[5];

                eleInfo.setElementValue(eleV);
                eleInfo.setElementCategory(eleCat);
                eleInfo.setElementMarkValue(eleMarkV);

                String[] allPos = eleVPos.split(" ");
                eleInfo.setAllStart(Integer.valueOf(allPos[0]));
                eleInfo.setAllEnd(Integer.valueOf(allPos[1]));

                eleInfo.setPage(Integer.valueOf(posStr.split(" ")[0]));
                eleInfo.setParaNo(Integer.valueOf(posStr.split(" ")[1]));
                eleInfo.setLineId(posStr.split(" ")[2]);

                eleInfo.setLineStart(Integer.valueOf(eleParaPos.split(" ")[0]));
                eleInfo.setLineEnd(Integer.valueOf(eleParaPos.split(" ")[1]));

                return eleInfo;
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("line data error!... content is <" + line + ">");
            }
            return null;
        }
    }

    // 将模型ocr json转换成web ocr json
    public static JSONArray transOCRJsonArr(String ocrArrPath) {
        JSONArray array = ConvertToJsonArray(ocrArrPath);
        doTransOCRJsonArr(array);

        return array;
    }

    public static void doTransOCRJsonArr(JSONArray array) {
        try {
            for (int i = 0; i < array.size(); i++) {

                JSONObject pageObj = array.getJSONObject(i);

                JSONArray lines = pageObj.getJSONArray("lineList");
                pageObj.remove("lineList");

                JSONObject paraObj = new JSONObject();
                paraObj.put("paraId", "0");
                paraObj.put("paraNo", 0);

                //根据ocr结果 web_visible 去掉重复orc内容
                JSONArray linesNew = getWebVisible(lines);

                paraObj.put("lines", linesNew);
                JSONArray paraArr = new JSONArray();
                paraArr.add(paraObj);

                pageObj.put("paragraphs", paraArr);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据ocr结果 web_visible 去掉重复orc内容
     *
     * @param lines
     * @return
     */
    private static JSONArray getWebVisible(JSONArray lines) {
        JSONArray linesNew = new JSONArray();
        for (int i1 = 0; i1 < lines.size(); i1++) {
            JSONObject line = lines.getJSONObject(i1);
            String webVisible = line.getString("web_visible");
            if (StringUtils.isEmpty(webVisible)) {
                linesNew.add(line);
            } else if (!StringUtils.isEmpty(webVisible) && !webVisible.equals("False")) {
                linesNew.add(line);
            }
        }
        return linesNew;
    }

    /*
     * 将OCR结果文件转换成json格式，并按照自然段分组
     * */
    public static JSONArray transOCRResultToParaType(String filePath) {
        List<String> lines = readFileByLines(filePath);
        System.out.println(lines);

        JSONArray resultArr = new JSONArray();

        if (lines.size() > 0) {
            for (String line : lines) {
                if (!StringUtils.isEmpty(line)) {
                    JSONObject paragraphObj = new JSONObject();
                    //                    System.out.println("paragraph parentTaskSn is: " + line.substring( line.lastIndexOf( "{{", line.lastIndexOf( "}}" ) ) ));
                    paragraphObj.put("paragraphId", line.substring(line.lastIndexOf("{{") + 2, line.lastIndexOf("}}")));
                    paragraphObj.put("paraId", line.substring(line.lastIndexOf("{{") + 2, line.lastIndexOf("}}")));
                    paragraphObj.put("paraNo", paragraphObj.getString("paraId").split("_")[1]);
                    String linesStr = line.substring(line.lastIndexOf("}}"), line.lastIndexOf("]]"));

                    List<String> linesList = cutLineStr("((", "))", linesStr);

                    //                    System.out.println( linesList );

                    if (linesList.size() > 0) {
                        JSONArray lineArr = new JSONArray();

                        for (String s : linesList) {
                            String lineId = null;
                            try {
                                lineId = s.substring(s.lastIndexOf("<<") + 2, s.lastIndexOf(">>"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            String text = s.substring(s.lastIndexOf(">>") + 2);

                            JSONObject lineObj = new JSONObject();
                            lineObj.put("text", text);
                            lineObj.put("lineId", lineId);
                            lineObj.put("objContent", text);
                            lineObj.put("objPos", "");
                            lineArr.add(lineObj);
                        }
                        paragraphObj.put("lines", lineArr);
                    }

                    resultArr.add(paragraphObj);
                }
            }
        }

        JSONObject obj = new JSONObject();
        obj.put("pageNo", 0);
        obj.put("docID", "");
        obj.put("paragraphs", resultArr);

        JSONArray result = new JSONArray();
        result.add(obj);
        return result;
    }

    public static JSONArray ConvertToJsonArray(String path) {

        JSONArray jsonArray = null;
        String jsonStr = getStringRemote(path);
        try {
            jsonArray = JSONArray.parseArray(jsonStr.trim());
        } catch (IllegalStateException | JSONException ex) {
            ex.printStackTrace();
        }
        return jsonArray;
    }

    public static JSONObject convertToJsonObj(String path) {

        JSONObject jsonObj = null;
        String jsonStr = getStringRemote(path);
        try {
            jsonObj = JSONObject.parseObject(jsonStr.trim());
        } catch (IllegalStateException | JSONException ex) {
            ex.printStackTrace();
        }
        return jsonObj;
    }

    private static String getStringRemote(String path) {
        BufferedReader reader = null;
        StringBuilder jsonStrs = new StringBuilder();
        InputStream inputStream = null;
        try {
            //绝对路径
            inputStream = new FileInputStream(path);

            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempStr = null;
            while ((tempStr = reader.readLine()) != null) {
                jsonStrs.append(tempStr);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (jsonStrs.length() > 0
                && !"null".equals(jsonStrs.toString())
                && !"".equals(jsonStrs.toString())) {
            return jsonStrs.toString();
        }
        return "";
    }

    private static List<String> cutLineStr(String startSplit, String endSplit, String textLine) {

        List<String> lines = new LinkedList<>();

        String t = textLine;

        String tmp = null;

        try {
            while (t.contains(startSplit)
                    && t.contains(endSplit)
                    && !(tmp = t.substring(t.indexOf(startSplit) + startSplit.length(), t.indexOf(endSplit))).equals("")) {
                t = t.substring(t.indexOf(endSplit) + endSplit.length());
                lines.add(tmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return lines;
    }

    public static List<String> readFileByLines(String fileName) {
        List<String> lines = new LinkedList<>();

        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;

            while ((tempString = reader.readLine()) != null) {
                lines.add(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return lines;
    }

    public static String readFile(String fileName) {

        StringBuilder result = new StringBuilder();
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;

            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return result.toString();
    }

    public static boolean writeFile(String filePath, String content, boolean append) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                boolean success = file.createNewFile();

            } catch (IOException e) {
                log.error("create file error. cleanTextPath = {},content = {},append = {} ", filePath, content, append, e);
                return false;
            }
        }

        try {
            FileWriter fileWriter = new FileWriter(filePath, append);
            fileWriter.write(content);
            fileWriter.flush();
            fileWriter.close();
            return true;
        } catch (IOException e) {
            log.error("write file error. cleanTextPath = {},content = {},append = {} ", filePath, content, append, e);
        }
        return false;
    }

    public static String loadJson(String url) {
        url = url.replaceAll("media.tlrobot.com","172.18.7.15:8111/");
        String tempPath = System.getProperty("java.io.tmpdir") + File.separator;
        String tmpFilePath = "";
        try {
            tmpFilePath = tempPath + URLEncoder.encode(url, "UTF-8");
            File tmpFile = new File(tmpFilePath);
            if (tmpFile.exists()) {
                return readFile(tmpFile.getAbsolutePath());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (!StringUtils.isEmpty(url) && !url.startsWith("http://") && !url.startsWith("https://")) {
            return FileUtils.readFile(url);
        }

        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!StringUtils.isEmpty(tmpFilePath)) {
            writeFile(tmpFilePath, json.toString(), false);
            File file = new File(tmpFilePath);
            file.deleteOnExit();
        }
        return json.toString();
    }

    public static File downloadFile(String urlPath) {
        try {
            urlPath = urlPath.replaceAll("media.tlrobot.com","172.18.7.15:8111/");
            File tempFile = File.createTempFile("temp", ".jpg");
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 5);
            //设置请求方式，默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 控制台打印文件大小
            log.info("您要下载的文件大小为:" + fileLength / (1024) + "KB");

            // 建立链接从请求中获取数据
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

            OutputStream out = new FileOutputStream(tempFile);
            int size;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                out.write(buf, 0, size);
            }
            // 关闭资源
            bin.close();
            out.close();
            return tempFile;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    static void doInterpolation(JSONArray array) {

        for (int i = 0; i < array.size(); i++) {

            JSONObject pageObj = array.getJSONObject(i);

            JSONArray lines = pageObj.getJSONArray("lineList");
            pageObj.remove("lineList");

            JSONObject paraObj = new JSONObject();
            paraObj.put("paraId", "0");
            paraObj.put("paraNo", 0);

            //根据ocr结果 web_visible 去掉重复orc内容
            JSONArray linesNew = FileUtils.getWebVisible(lines);

            paraObj.put("lines", linesNew);
            JSONArray paraArr = new JSONArray();
            paraArr.add(paraObj);

            pageObj.put("paragraphs", paraArr);

        }

        for (int j = 0; j < array.size(); j++) {
            JSONObject jsonObject = array.getJSONObject(j);

            String docID = jsonObject.getString("docID");
            String pageNo = jsonObject.getString("pageNo");

            jsonObject.remove("contIndex");

            JSONArray paragraphs = jsonObject.getJSONArray("paragraphs");

            JSONObject paraObj = paragraphs.getJSONObject(0);

            JSONArray lines = paraObj.getJSONArray("lines");

            JSONArray resLines = new JSONArray();

            //                        JSONObject lastObj = lines.getJSONObject( lines.size() );
            //                        Integer totalLineNo = lastObj.getInteger( "lineNo" );

            for (int k = 0; k < lines.size(); k++) {

                JSONObject lineObj = lines.getJSONObject(k);
                Integer lineNo = lineObj.getInteger("lineNo");

                while (resLines.size() < lineNo) {
                    int size = resLines.size();
                    JSONObject emptyLine = new JSONObject();
                    emptyLine.put("lineId", "line_" + pageNo + "_" + size + "_cusline" + size);
                    emptyLine.put("lineNo", size);
                    emptyLine.put("objContent", "");

                    JSONArray emptyPos = new JSONArray();
                    emptyPos.add(0);
                    emptyPos.add(0);
                    emptyPos.add(0);
                    emptyPos.add(0);
                    emptyLine.put("objPos", emptyPos);

                    emptyLine.put("objType", "textLine");

                    System.out.println(">>>>>>> adding empty line , page " + pageNo + ", before line " + lineNo + ", added line " + size);

                    resLines.add(emptyLine);
                }

                resLines.add(lineObj);
            }

            paraObj.put("lines", resLines);
        }
    }

    /**
     * 将multipartFile转成File
     *
     * @param filePath      文件绝对路径，包含文件名
     * @param multipartFile multipartFile
     * @return java.io.File
     * @author lcy
     * @date 2021/5/14 18:20
     **/
    public static File multipartFileToFile(String filePath, MultipartFile multipartFile) {
        File file = new File(filePath);
        try {

            //创建文件
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists() && !file.isDirectory()) {
                file.createNewFile();
            }
            multipartFile.transferTo(file);
        } catch (IOException e) {
            Log.error("multipartFile to file failed. cleanTextPath={} ", filePath, e);
            return null;
        }
        return file;
    }

    /**
     * 将multipartFile转成File
     *
     * @param filePath      文件路径
     * @param fileName      文件名
     * @param multipartFile multipartFile
     * @return java.io.File
     * @author lcy
     * @date 2021/5/14 18:20
     **/
    public static File multipartFileToFile(String filePath, String fileName, MultipartFile multipartFile) {
        return multipartFileToFile(filePath + File.separator + fileName, multipartFile);
    }

    /**
     * 将File转成multipartFile
     *
     * @param file file
     * @return org.springframework.web.multipart.MultipartFile
     * @author lcy
     * @date 2021/5/14 18:26
     **/
    public static MultipartFile fileToMultipartFile(File file) {
        try (InputStream inputStream = new FileInputStream(file)) {
            return new MockMultipartFile(file.getName(), inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过二进制字节流，读取指定输入流
     *
     * @param inputStream 二进制流
     * @return java.lang.String
     * @author lcy
     * @date 2021/4/25 15:43
     **/
    public static String readByInputStream(InputStream inputStream) {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
            //这是指定每次读取1024个字节
            byte[] bytes = new byte[1024];
            int read = 0;
            while ((read = bufferedInputStream.read(bytes, 0, read)) != -1) {
                //可以指定编码读取
                stringBuilder.append(new String(bytes));
            }
        } catch (IOException e) {
            Log.error("读取流异常 ", e);
            return "";
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.error("关闭流异常 ", e);
                }
            }
        }
        return stringBuilder.toString();
    }

    public static boolean copyFile(File oldFile, File newFile) {

        try {
            org.apache.commons.io.FileUtils.copyFile(oldFile, newFile);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            assert children != null;
            for (String child : children) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

}
